<?php

namespace Fluency\Web\Routing;

use Fluency\Web\Http\Request;

/**
 * A decorator for routers that queries the underlying router with an URL that has its extension
 * part (the one after the last dot) detached, and returns a modified request with the content type
 * field set to the value retrieved from the initial URL.
 *
 * @package Fluency\Web\Routing
 * @author  Ignas Rudaitis
 * @since   1.0
 */
class FormatCapturer implements Router
{
    private $router;

    /**
     * The constructor.
     *
     * @param Fluency\Web\Routing\Router $router the router to decorate
     */
    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    /**
     * @see Fluency\Web\Routing\Router::query()
     *
     * @param string $url
     * @return Fluency\Web\Http\Request|null
     */
    public function query($url)
    {
        $url = str_replace("//", "/", trim($url, "/"));
        $format = null;
        if (strpos($url, ".")) {
            $segments = explode(".", $url);
            $format = array_pop($segments);
            $url = join(".", $segments);
        }
        $req = $this->router->query($url);
        if ($req !== null) {
            if ($format !== null) {
                $req = $req->withFormat($format);
            }
            return $req;
        }
    }
}
